//
//  WH_ListViewController.m
//  App_6.23
//
//  Created by 芦珊 on 16/6/24.
//  Copyright © 2016年 lushan. All rights reserved.
//

#import "WH_ListViewController.h"
#import "WH_ListTableViewCell.h"
#import "WH_HomeDetailController.h"
#import "AppDelegate.h"
#import "LS_ListCollectionViewCell.h"
#import "WH_Home.h"
#import "WH_CheckViewController.h"
#import "WH_ListOrder.h"

@interface WH_ListViewController ()<UITableViewDataSource,UITableViewDelegate,headToHomeDetail,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>{
    
    NSInteger cart_total;//清单总人次
    NSInteger cart_quantity;//清单产品数量
}

@property (nonatomic ,strong)UITableView *listTableView;
@property (nonatomic ,strong)UIView *totleView;
@property (nonatomic ,strong)UIView *chooseView;
@property (nonatomic ,assign)BOOL editState; //编辑按钮bool值

@property (nonatomic ,strong)UIButton *allChooseBtn;
@property (nonatomic ,strong)UIButton *totleBtn;

@property (nonatomic ,strong)NSMutableArray *listArray;


@property (nonatomic ,strong)UICollectionView *listCollectionView;
@property (nonatomic ,strong)NSMutableArray *dataArr;
@property (nonatomic ,strong)NSMutableArray *cartArr;
@property (nonatomic, strong) NSMutableArray *periodArr;//接收传过来的期号
@property (nonatomic, strong) UILabel *rmbLabel;//价格
@property (nonatomic, assign) BOOL allS;
@property (nonatomic, assign) BOOL isUploading;//判断下拉刷新

@end

@implementation WH_ListViewController

//页面将要出现的方法
- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    [self postWorking];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.title = @"清单";
    self.editState = true;
    self.cartArr = [NSMutableArray array];
    self.periodArr = [NSMutableArray array];
    
    
    [self creatListTableView];
    [self createChooseView];
    [self createTotalView];
    [self createPriceLabel];
    [self createEmptylist];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"cart"] isEqualToString:@"1"]) {
        
        [self.view bringSubviewToFront:self.listTableView];
        [self.view bringSubviewToFront:self.totleView];
    }
    
}

-(void)postWorking{
    
    NSString *body = [NSString stringWithFormat:@"action=cart&user_id=%@",NSUSERID];
    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        [self.cartArr removeAllObjects];
        // NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSArray *cart_array = [dic objectForKey:@"cart_array"];
        cart_quantity = [[dic objectForKey:@"cart_quantity"] integerValue];
        cart_total = [[dic objectForKey:@"cart_total"] integerValue];
        self.rmbLabel.text = [NSString stringWithFormat:@"共%ld件商品,总计:%ld元",(long)cart_quantity,(long)cart_total];
        NSString *str1 = [NSString stringWithFormat:@"%ld元",(long)cart_total];
        [WH_AppTools changeColor:self.rmbLabel.text color:[UIColor redColor] xx:str1 nn:self.rmbLabel];
        if ([ISLOGIN isEqualToString:@"1"]) {
            
            if (cart_quantity == 0) {
                
                self.navigationItem.rightBarButtonItem = nil;
                [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"cart"];
                [self bringSubView];
            }else{
                
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleDone target:self action:@selector(rightButtonAction)];
                [self.view bringSubviewToFront:self.listTableView];
                [self.view bringSubviewToFront:self.totleView];
                if (_editState == NO) {
                    
                    [self.view bringSubviewToFront:self.chooseView];
                    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(rightButtonAction)];
                }
                [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"cart"];
            }
            
        }else{
            self.navigationItem.rightBarButtonItem = nil;
            [self bringSubView];
            
        }
        for (NSDictionary *dic in cart_array) {
                
            WH_Home *product = [WH_Home modelWithDictionary:dic];
            
            product.selected = _allS;
            [self.cartArr addObject:product];
            
            
        }
        [self.listTableView reloadData];
        [self.listTableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
            
            
    }];
        
        
}

//创建清单tableview
- (void)creatListTableView{
    
    self.listTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.bounds.origin.x - ((SCREEN_HEIGHT / 5) / 3), self.view.bounds.origin.y, SCREEN_WIDTH + ((SCREEN_HEIGHT / 5) / 3), SCREEN_HEIGHT - 49-49) style:UITableViewStylePlain];
    self.listTableView.dataSource = self;
    self.listTableView.delegate = self;
    [self.listTableView registerClass:[WH_ListTableViewCell class] forCellReuseIdentifier:@"listCell"];
    self.listTableView.rowHeight = SCREEN_HEIGHT / 5;
    [self.view addSubview:_listTableView];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerTab)];
    self.listTableView.mj_header = header;
    self.listTableView.tableFooterView = [UIView new];
}

#pragma mark - 刷新
-(void)headerTab{
    
    [self postWorking];
}

#pragma mark -结算view
- (void)createTotalView{
    
    self.totleView = [[UIView alloc] init];
    self.totleView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_totleView];
    
    [self.totleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(@-49);
        make.height.equalTo(@49);
    }];
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor colorWithRed:0.86 green:0.85 blue:0.86 alpha:1];
    [self.totleView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(@0);
        make.top.equalTo(self.totleView.mas_top);
        make.height.equalTo(@1);
    }];
    
    self.totleBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.totleBtn setTitle:@"结算" forState:UIControlStateNormal];
    [_totleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _totleBtn.backgroundColor = [UIColor colorWithRed:0.86 green:0.21 blue:0.32 alpha:1];
    _totleBtn.layer.cornerRadius = 5;
    [self.totleBtn addTarget:self action:@selector(totleBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.totleView addSubview:self.totleBtn];
    
    [self.totleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.totleView.mas_right).offset(-30);
        make.top.equalTo(self.totleView.mas_top).offset(10);
        make.bottom.equalTo(self.totleView.mas_bottom).offset(-10);
        make.width.equalTo(@60);
    }];
    
}

- (void)createPriceLabel{
    self.rmbLabel = [[UILabel alloc] init];
    //_rmbLabel.backgroundColor = [UIColor orangeColor];
    
    _rmbLabel.font = [UIFont systemFontOfSize:15];

    [self.totleView addSubview:_rmbLabel];
    
    [self.rmbLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.totleView.mas_left).offset(30);
        make.top.equalTo(self.totleView.mas_top).offset(10);
        make.bottom.equalTo(self.totleView.mas_bottom).offset(-10);
        make.width.equalTo(@(200*WID_ONE));
    }];
}

#pragma mark - cell协议方法

-(void)freshView{
    
    [self headerTab];
}

#pragma mark -全选view
- (void)createChooseView{
    
    self.chooseView = [[UIView alloc] init];
    self.chooseView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_chooseView];
    
    [self.chooseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(@-49);
        make.height.equalTo(@49);
    }];
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor colorWithRed:0.86 green:0.85 blue:0.86 alpha:1];
    
    [self.chooseView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(@0);
        make.top.equalTo(self.chooseView.mas_top);
        make.height.equalTo(@1);
    }];

    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [deleteBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    deleteBtn.layer.cornerRadius = 5;
    deleteBtn.layer.borderWidth = .3;
    deleteBtn.layer.borderColor = [UIColor redColor].CGColor;
    [deleteBtn addTarget:self action:@selector(deleteBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.chooseView addSubview:deleteBtn];
    
    [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.chooseView.mas_right).offset(-30);
        make.top.equalTo(self.chooseView.mas_top).offset(10);
        make.bottom.equalTo(self.chooseView.mas_bottom).offset(-10);
        make.width.equalTo(@60);
    }];
    
    
    //全选按钮
    self.allChooseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.allChooseBtn setBackgroundImage:[UIImage imageNamed:@"圆形未选中.png"] forState:UIControlStateNormal];
    [self.allChooseBtn addTarget:self action:@selector(allChooseAction) forControlEvents:UIControlEventTouchUpInside];
    self.allChooseBtn.selected = true;
    [self.chooseView addSubview:self.allChooseBtn];
    [self.allChooseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.chooseView.mas_left).offset(12);
        make.top.equalTo(self.chooseView.mas_top).offset((49 - ((SCREEN_HEIGHT / 5) / 5)) / 2);
        make.height.width.equalTo(@((SCREEN_HEIGHT / 5) / 5));
    }];
    
    
    UILabel *allLabel = [[UILabel alloc] init];
    allLabel.text = @"全选";
    allLabel.textColor = [UIColor lightGrayColor];
    allLabel.font = [UIFont systemFontOfSize:15];
    [self.chooseView addSubview:allLabel];
    [allLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.allChooseBtn.mas_right).offset(5);
        make.top.equalTo(self.chooseView.mas_top).offset((49 - ((SCREEN_HEIGHT / 5) / 5)) / 2);
        make.height.equalTo(@((SCREEN_HEIGHT / 5) / 5));
        make.width.equalTo(@30);
    }];
    
}
#pragma mark -全选按钮响应方法
- (void)allChooseAction{
    
    if (self.allChooseBtn.selected == true) {
        self.allChooseBtn.selected = false;
        
        [self.periodArr removeAllObjects];
        [self.allChooseBtn setBackgroundImage:[UIImage imageNamed:@"圆形选中.png"] forState:UIControlStateNormal];
        _allS = YES;
        for (WH_Home *periodH in self.cartArr) {
            
            [self.periodArr addObject:periodH.product_period];
        }
        [self postWorking];
        NSLog(@"====periodArr == %ld",(unsigned long)self.periodArr.count);
    }else{
        [self.allChooseBtn setBackgroundImage:[UIImage imageNamed:@"圆形未选中.png"] forState:UIControlStateNormal];
        _allS = NO;
        [self.periodArr removeAllObjects];
        [self postWorking];
        NSLog(@"-----peroidArr=%ld",(unsigned long)_periodArr.count);
        self.allChooseBtn.selected = true;
    }
    
    [self.view bringSubviewToFront:_chooseView];
    //self.allChooseBtn.selected = !self.allChooseBtn.selected;
}

-(void)sendModelToC:(WH_Home *)peroidModel{
    
    [self.periodArr addObject:peroidModel.product_period];
    
    if (_periodArr.count == _cartArr.count) {
        
        [self.allChooseBtn setBackgroundImage:[UIImage imageNamed:@"圆形选中.png"] forState:UIControlStateNormal];
        self.allChooseBtn.selected = false;

    }
    NSLog(@"peroidArr=%ld",_periodArr.count);
}

-(void)deleModelToC:(WH_Home *)peroidModel{
    
    [self.periodArr removeObject:peroidModel.product_period];
    
    if (_allS == YES || _periodArr.count != _cartArr.count) {
        
        [self.allChooseBtn setBackgroundImage:[UIImage imageNamed:@"圆形未选中.png"] forState:UIControlStateNormal];
        self.allChooseBtn.selected = true;
    }
    NSLog(@"peroidArr=%ld",_periodArr.count);

}
#pragma mark -删除按钮响应方法
- (void)deleteBtnAction:(UIButton *)btn{
    NSLog(@"删除按钮");
    NSLog(@"-----peroidArr=%ld",(unsigned long)_periodArr.count);

    if (_periodArr.count == 0) {
        
        [WSProgressHUD showImage:nil status:@"请选择商品" maskType:WSProgressHUDMaskTypeClear];
        return;
    }
    [self alertViewControllerWithTitle:@"确定删除吗" content:@"" block:^{
        
        for (NSString *periodH in self.periodArr) {
            
            NSString *body = [NSString stringWithFormat:@"action=cart_del&user_id=%@&product_period=%@", NSUSERID,periodH];
            [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
                
                // NSLog(@"%@",result);
                NSDictionary *dic = result;
                NSString *status = [dic objectForKey:@"status"];
                NSString *message = [dic objectForKey:@"message"];
                if ([status isEqualToString:@"success"]) {
                    
                    [self.periodArr removeAllObjects];
                    [self.allChooseBtn setBackgroundImage:[UIImage imageNamed:@"圆形未选中.png"] forState:UIControlStateNormal];
                    self.listTableView.frame = CGRectMake(self.view.bounds.origin.x - ((SCREEN_HEIGHT / 5) / 3), self.view.bounds.origin.y, SCREEN_WIDTH + ((SCREEN_HEIGHT / 5) / 3), SCREEN_HEIGHT - 49);
                    
                    if (_allS == YES) {
                        
                        _allS = NO;
                        
                    }
                    _editState = true;
                    self.allChooseBtn.selected = true;
                    [self postWorking];
                    
                }else{
                    
                    [WSProgressHUD showImage:nil status:message];
                    
                }
                
            } failure:^(NSError *error) {
                
                
            }];
            
        }

        
    }];
    

    
}
#pragma mark - 显示空表

-(void)QQbringSubView{
    
    UIImageView *imageV = (UIImageView *)[self.view viewWithTag:20001];
    UILabel *label = (UILabel *)[self.view viewWithTag:20002];

    [self.view bringSubviewToFront:self.listCollectionView];
    [self.view bringSubviewToFront:imageV];
    [self.view bringSubviewToFront:label];
}

#pragma mark -结算按钮响应方法
- (void)totleBtnAction:(UIButton *)btn{
    NSLog(@"结算按钮");
    
    WH_CheckViewController *chectVC = [[WH_CheckViewController alloc] init];
    chectVC.modelArr = self.cartArr;
    chectVC.orderCount = cart_quantity;
    chectVC.orderPrice = cart_total;
    [self.navigationController pushViewController:chectVC animated:YES];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.cartArr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellId = @"listCell";
    WH_ListTableViewCell *listCell = [tableView dequeueReusableCellWithIdentifier:cellId];
    listCell.headdelegate = self;
    listCell.selectionStyle = UITableViewCellSeparatorStyleNone;
    listCell.homeModel = self.cartArr[indexPath.row];
    listCell.indexRow = indexPath.row;
    return listCell;
    
}


#pragma mark -编辑按钮响应方法
- (void)rightButtonAction{
    
    [UIView animateWithDuration:0.5 animations:^{
        self.listTableView.frame = CGRectMake((self.view.bounds.origin.x + ((SCREEN_HEIGHT / 5) / 3)), self.view.bounds.origin.y, SCREEN_WIDTH, SCREEN_HEIGHT - 49);
    }];
    
    if (self.editState == true) {
        [self.view bringSubviewToFront:self.chooseView];
        
        [UIView animateWithDuration:0.5 animations:^{
            self.listTableView.frame = CGRectMake((self.view.bounds.origin.x), self.view.bounds.origin.y, SCREEN_WIDTH, SCREEN_HEIGHT - 49);
        }];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(rightButtonAction)];
        [self.listTableView.mj_header setHidden:YES];
        //NSLog(@"11");
    }else{
        [self.view bringSubviewToFront:self.totleView];
        
        [UIView animateWithDuration:0.5 animations:^{
            self.listTableView.frame = CGRectMake(self.view.bounds.origin.x - ((SCREEN_HEIGHT / 5) / 3), self.view.bounds.origin.y, SCREEN_WIDTH + ((SCREEN_HEIGHT / 5) / 3), SCREEN_HEIGHT - 49);
        }];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleDone target:self action:@selector(rightButtonAction)];
        //NSLog(@"00")
        [self.listTableView.mj_header setHidden:NO];

    }
    self.editState = !self.editState;
    //NSLog(@"%ld",self.editState);
}

- (void)headImgPush:(NSString *)productId{
 
    WH_HomeDetailController *homeDetail = [[WH_HomeDetailController alloc] init];
    homeDetail.productID = productId;
    [self.navigationController pushViewController:homeDetail animated:YES];
}

#pragma mark -创建空的清单 20001
- (void)QQcreateEmptyList{
    
    self.navigationItem.rightBarButtonItem = nil;
    UIImageView *imgView = [[UIImageView alloc] init];
    imgView.tag = 20001;
    imgView.image = [UIImage imageNamed:@"cartImage"];
    imgView.userInteractionEnabled = YES;
    [self.view addSubview:imgView];
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.right.top.equalTo(self.view);
        make.height.equalTo(@(SCREEN_HEIGHT));
        
    }];
    //添加tap
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imBtnAction)];
    [imgView addGestureRecognizer:tap];
    
    //[self createListCV];
    [self postData];
}
#pragma mark - 20002

- (void)createListCV{
    
    UILabel *likeLabel = [[UILabel alloc] init];
    likeLabel.tag = 20002;
    likeLabel.backgroundColor = [UIColor whiteColor];
    likeLabel.text = @"   猜你喜欢";
    likeLabel.font = [UIFont systemFontOfSize:15];
    likeLabel.textColor = [UIColor grayColor];
    [self.view addSubview:likeLabel];
    [likeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset((SCREEN_HEIGHT / 5 * 3-64));
        make.width.equalTo(@(SCREEN_WIDTH));
        make.height.equalTo(@40);
        
    }];
    
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //section内置大小(距离每个分区的上下左右大小)
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    //item大小(itemSize大小都一样,是这样写,且不使用代理方法返回大小)
    flowLayout.itemSize = CGSizeMake(((SCREEN_WIDTH - 30) / 3), (SCREEN_HEIGHT / 5 * 2) - 109);
    
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.listCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, (SCREEN_HEIGHT / 5 * 3 + 40-64), SCREEN_WIDTH, (SCREEN_HEIGHT / 5 * 2) - 89) collectionViewLayout:flowLayout];
    self.listCollectionView.delegate = self;
    self.listCollectionView.dataSource = self;
    [self.view addSubview:self.listCollectionView];
    [self.listCollectionView registerClass:[LS_ListCollectionViewCell class] forCellWithReuseIdentifier:@"LS_ListCollectionViewCell"];
    self.listCollectionView.backgroundColor = [UIColor whiteColor];
    
}

- (void)imBtnAction{
    
    //UIApplication是系统单例,可以直接使用
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    appDelegate.tabbarMain.selectedIndex = 0;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *itemId = @"LS_ListCollectionViewCell";
    LS_ListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:itemId forIndexPath:indexPath];
    
//        cell.backgroundColor = [UIColor whiteColor];
    cell.homeModel = [self.dataArr objectAtIndex:indexPath.row];
    
    return cell;
}

-(void)postData{
    
    self.dataArr = [NSMutableArray array];
    
    NSString *body = @"action=index_product";
    
    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        
        // NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSArray *product_array = [dic objectForKey:@"product_array"];
        
        for (NSDictionary *dic in product_array) {
            
            WH_Home *product = [WH_Home modelWithDictionary:dic];
            [self.dataArr addObject:product];
        }
        [self.listCollectionView reloadData];
        //NSLog(@"%lu",(unsigned long)self.dataArr.count);
    } failure:^(NSError *error) {
        
        
    }];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
